<template>
  <div class="news-management">
    <!-- 表格区域 -->
    <div class="table-container">
      <catch-table :form-create="formCreate" v-bind="table"/>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="80%"
      title="新闻编辑"
      :close-on-click-modal="false"
    >
      <div class="news-form">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="right"
          class="form-container"
        >
          <!-- 基础信息行（两列布局） -->
          <el-row :gutter="20">
            <!-- 左侧列 -->
            <el-col :span="12">
              <!-- 标题 -->
              <el-form-item label="标题" prop="title">
                <el-input
                  v-model="form.title"
                  placeholder="请输入标题"
                  maxlength="100"
                  show-word-limit
                ></el-input>
              </el-form-item>

              <!-- 分类 -->
              <el-form-item label="分类" prop="news_class_id">
                <el-select
                  v-model="form.news_class_id"
                  placeholder="请选择分类"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in classOptions"
                    :key="item.id"
                    :label="item.class_name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="轮播图" prop="banner_is">
                <el-select
                  v-model="form.banner_is"
                  placeholder="请选择是否banner图片"
                  style="width: 100%"
                >
                  <el-option label="不是" :value="1"></el-option>
                  <el-option label="是" :value="2"></el-option>
                </el-select>
              </el-form-item>
              <!-- 发布人 -->
              <el-form-item label="发布人" prop="fa_name">
                <el-input
                  v-model="form.fa_name"
                  placeholder="请输入发布人姓名"
                  maxlength="20"
                ></el-input>
              </el-form-item>
              <el-form-item label="排序" prop="sort">
                <el-input-number
                  v-model="form.sort"
                  :min="0"
                  :max="1000"
                  placeholder="数字越大越靠前"
                ></el-input-number>
              </el-form-item>
            </el-col>

            <!-- 右侧列 -->
            <el-col :span="12">
              <!-- 封面 -->
              <el-form-item label="封面" prop="cover">
                <!-- :action="`https://dian18.cn/upload/image?file_type=3`" -->
                <el-upload
                  class="cover-uploader"
                  :action="`${baseApi}/upload/image?file_type=3`"
                  :show-file-list="false"
                  :on-success="handleCoverSuccess"
                  :before-upload="beforeCoverUpload"
                >
                  <!-- <img
                    v-if="form.cover"
                    :src="form.cover"
                    class="cover-image"
                  /> -->
                  <el-image
                    class="cover-image"
                    v-if="form.cover"
                    :src="form.cover"
                    :fit="fit"
                  ></el-image>
                  <i v-else class="el-icon-plus cover-uploader-icon"></i>
                </el-upload>
                <div class="upload-tip">
                  建议尺寸：600*400px，支持jpg、png格式
                </div>
              </el-form-item>

              <!-- 排序 -->
            </el-col>
          </el-row>

          <!-- 内容编辑器（占满一行） -->
          <el-form-item label="正文内容" prop="content">
            <div class="editor-wrapper">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 400px; overflow-y: auto"
                v-model="form.content"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="onCreated"
                @onChange="onChange"
              />
            </div>
          </el-form-item>

          <!-- 按钮区域 -->
          <el-form-item class="form-actions">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import renderTable from '@/views/render-table-form'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'

export default {
  mixins: [renderTable],
  components: { Editor, Toolbar },
  data() {
    return {
      baseApi: process.env.VUE_APP_BASE_API,
      tableFrom: '',
      dialogVisible: false,
      editor: null,
      mode: 'default',
      // 编辑器配置
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            server: `${process.env.VUE_APP_BASE_API}/upload/imageUrl?file_type=3`,
            fieldName: 'file',
            maxFileSize: 2 * 1024 * 1024,
            headers: {
              Authorization: 'Bearer ' + getToken()
            },
            onSuccess: (file, res) => {
              console.log('上传成功', res)
            },
            onFailed: (file, res) => {
              console.error('上传失败', res)
              Message.error('图片上传失败，请重试')
            },
            onError: (file, err, res) => {
              const isLt2M = file.size <= 2 * 1024 * 1024
              if (!isLt2M) {
                Message.error('图片大小不能超过2MB，请压缩后再上传')
                return false // 阻止上传
              } else {
                Message.error('上传发生错误：' + (err.message || '未知错误'))
              }
            }
          }
        }
      },
      // 表单数据
      form: {
        title: '',
        content: '',
        news_class_id: null,
        cover: '',
        view_count: 0,
        sort: 0,
        fa_name: '',
        banner_is: 1
      },
      // 分类选项
      classOptions: [],
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          {
            min: 2,
            max: 100,
            message: '标题长度在 2-100 个字符',
            trigger: 'blur'
          }
        ],
        banner_is: [
          { required: true, message: '请选择是否banner图', trigger: 'change' }
        ],
        news_class_id: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        fa_name: [
          { required: true, message: '请输入发布人', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '发布人名称在 2-20 个字符',
            trigger: 'blur'
          }
        ],
        content: [
          { required: true, message: '请输入正文内容', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.newsType()
  },
  methods: {
    newsType() {
      this.$http({
        url: '/newsClass?news_is=1',
        method: 'get'
      }).then((r) => {
        if (r.code == 10000) {
          this.classOptions = r.data
        }
      })
    },
    editNews(e) {
      console.log(e)

      this.dialogVisible = true

      this.$http({
        url: '/news/' + e.id,
        method: 'get'
      }).then((r) => {
        if (r.code == 10000) {
          this.form = r.data
        }
      })
    },
    beforeSubmit(row) {
      if (row.form.parent_id instanceof Array) {
        row.form.parent_id =
          row.form.parent_id.length > 0 ? row.form.parent_id.pop() : 0
      }
      return row
    },
    zidingyi(e) {
      console.log(e)
    },
    handleCreate1() {
      this.dialogVisible = true
      // 重置表单
      this.$nextTick(() => {
        this.$refs.form.resetFields()
      })
    },
    // 编辑器初始化
    onCreated(editor) {
      this.editor = Object.seal(editor)
    },
    onChange(editor) {
      this.form.content = editor.getHtml() // 同步HTML内容
    },
    // 封面上传成功
    handleCoverSuccess(res) {
      if (res.code === 10000) {
        this.form.cover = res.data.web_url
        this.form.url = res.data.url
        Message.success('封面上传成功')
      } else {
        console.log(res)
        Message.error('封面上传失败：' + (res.message || '未知错误'))
      }
    },
    // 封面上传前校验
    beforeCoverUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        Message.error('只能上传图片文件！')
        return false
      }
      if (!isLt2M) {
        Message.error('上传图片大小不能超过 2MB！')
        return false
      }
      return true
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.form.id) {
            this.$http({
              url: 'news',
              method: 'POST',
              data: this.form
            }).then((r) => {
              // console.log(r);
              if (r.code == 10000) {
                Message.success('新增成功')
                this.dialogVisible = false
                this.$refs.form.resetFields()
                this.$refs.catchTable.getList()
              } else {
                Message.error(r.msg)
              }
            })
          } else {
            this.$http({
              url: `news/${this.form.id}`,
              method: 'put',
              data: this.form
            }).then((r) => {
              // console.log(r);
              if (r.code == 10000) {
                Message.success('修改成功')
                this.dialogVisible = false
                this.$refs.form.resetFields()
                this.$refs.catchTable.getList()
              } else {
                Message.error(r.msg)
              }
            })
          }
          //   this.$http({
          //     url: "news",
          //     method: "POST",
          //     data: this.form,
          //   }).then((r) => {

          //     // console.log(r);
          //     if (r.code == 10000) {
          //       Message.success("新增成功");
          //     } else {
          //       Message.error(r.msg);
          //     }
          //   });
        } else {
          Message.error('请完善表单信息')
          return false
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.form.resetFields()
      if (this.editor) {
        this.editor.clear() // 清空编辑器
      }
    }
  },
  beforeDestroy() {
    // 销毁编辑器
    if (this.editor) {
      this.editor.destroy()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-upload {
  width: 100% !important;
}

.news-management {
  padding: 20px;
  background-color: #f5f7fa;
}

.table-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  padding: 15px;
  margin-bottom: 20px;
}

/* 表单样式 */
.news-form {
  padding: 10px 0;
}

.form-container {
  max-width: 100%;
  margin: 0 auto;
}

/* 编辑器样式 */
.editor-wrapper {
  border: 1px solid #e5e6eb;
  border-radius: 4px;
  overflow: hidden;
}

/* 封面上传样式 */
.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
  transition: border-color 0.3s;
  background-color: #fafafa; // 添加浅色背景
  height: auto;

  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .cover-image {
    width: 100%;
    height: 100%;
    object-fit: cover; // 或使用 contain 根据需求
    display: block;
  }
}

.cover-uploader:hover {
  border-color: #1890ff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 200px;
  line-height: 200px;
  text-align: center;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #8c8c8c;
  line-height: 1.5;
}

/* 按钮区域 */
.form-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e5e6eb;
}

.form-actions .el-button {
  margin: 0 8px;
  min-width: 100px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-row {
    display: block;
  }
  .el-col {
    width: 100% !important;
    margin-bottom: 15px;
  }
  .editor-wrapper {
    height: 300px;
  }
  .cover-uploader {
    height: 150px;
  }
  .cover-uploader-icon {
    height: 150px;
    line-height: 150px;
  }
}
</style>
